﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace VideoServer.Helpers
{
    //自定义命令类
    public class RelayCommand : ICommand
    {
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        event EventHandler _internalCanExecuteChanged;


        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {

        }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }
        //当需要手动触发可执行状态改变时调用此方法，需在UI线程中调用此方法。
        //举例：APP.Current.MainWindow.Dispather.Invoke(new Action(()=>( xxCommand.RaiseCanExecuteChanged();)));
        public void RaiseCanExecuteChanged()
        {
            if (_canExecute != null)
                OnCanExecutedChanged();
        }
        protected virtual void OnCanExecutedChanged()
        {
            EventHandler eCanExecuteChanged = _internalCanExecuteChanged;
            if (eCanExecuteChanged != null)
                eCanExecuteChanged(this, EventArgs.Empty);
        }
        public event EventHandler CanExecuteChanged
        {
            add { _internalCanExecuteChanged += value; CommandManager.RequerySuggested += value; }
            remove { _internalCanExecuteChanged -= value; CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}
